#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const archiver = require("archiver"); // 用于生成打包文件

const DEST_DIR = path.join(__dirname, "../dist");
const DEST_ZIP_DIR = path.join(__dirname, "../dist-zip");

// 获取打包信息
const extractExtensionData = () => {
  const extPackageJson = require("../package.json");
  return {
    name: extPackageJson.name,
    version: extPackageJson.version,
  };
};

// 创建对应目录
const makeDestZipDirIfNotExists = () => {
  if (!fs.existsSync(DEST_ZIP_DIR)) {
    fs.mkdirSync(DEST_ZIP_DIR);
  }
};

const buildZip = (src, dist, zipFilename) => {
  console.info(`Building ${zipFilename}...`);
  const archive = archiver("zip", { zlib: { level: 9 } }); // level 压缩级别
  const stream = fs.createWriteStream(path.join(dist, zipFilename));
  return new Promise((resolve, reject) => {
    archive
      .directory(src, false)
      .on("error", (err) => reject(err))
      .pipe(stream);

    stream.on("close", () => resolve("Compression success ok!"));
    archive.finalize();
  });
};

const main = () => {
  const { name, version } = extractExtensionData();
  const zipFilename = `${name}-v${version}.zip`;
  // 创建对应存放压缩包目录
  makeDestZipDirIfNotExists();
  // 进行打包处理
  buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename)
    .then((res) => console.info(res))
    .catch(console.err);
};

main();

// 此模块用于打包生成压缩文件
